<template>
  <view class="change-delivery-container">
    <view class="stop-delivery-label">
      <view class="left">
        1.选择改奶日期
        <checkbox-group class="checked-box" @change="checkboxChange">
          <label>
              <checkbox class="checked-box-value" value="1" color="#fa436a" />全选
          </label>
        </checkbox-group>
      </view>
      <text class="right">已选{{selectedDays.length}}天</text>
    </view>
    <scroll-view
      scroll-y
      class="delivery-plan-container"
    >
      <view class="delivery-plan">
        <view 
          v-for="(item, index) in deliveryPlanList" 
          :key="item.deliveryDate" 
          class="delivery-day-item"
          :class="{active: selectedDays.indexOf(item.deliveryDate) > -1}"
          @click="selectDeliveryDate(item,index)"
        >
          {{item.deliveryDate | formatDate}}
        </view>
      </view>
    </scroll-view>
    
    <view class="stop-delivery-label">
      <view class="left">
        2.选择要更换的奶
      </view>
    </view>
    <!-- 商品列表 -->
    <scroll-view 
      scroll-y
      @scrolltolower="loadMore"
      class="good-list"
    >
    <block
      v-for="(goodItem, goodIndex) in goodList"
      :key="goodIndex"
    >
      <view
        v-if="deliveryGoodId !== goodItem.goodId"
        class="good-item"

      >
        <view class="good-item-info">
          <image
            class="good-item-info-l"
            :src="goodItem.goodImgs && goodItem.goodImgs[0]"
            mode="aspectFill"
          />
          <view class="good-item-info-r">
            <text>{{goodItem.goodName}}</text>
            <text class="good-price">￥ {{goodItem.goodPrice}}</text>
          </view>
        </view>
        <view
          type="primary"
          class="good-item-btn"
          :class="{active: selectedGoodId === goodItem.goodId}"
          @click="changeGood(goodItem)"
        >
          改为此款
        </view>
      </view>
    </block>
    <uni-load-more :status="loadingType" />
    </scroll-view>
    <!-- 确认按钮行 -->
    <view class="order-detail-btns">
      <view class="amount-container">
        费用：
        <text class="pay-amount">￥{{priceAmount !== 0 ? priceAmount : sumPremium}}</text>
      </view>
      <view class="amount-btn">
        <button 
          type="warn" 
          class="pay-btn"
          :class="{disabled: disabled}"
          :disabled="disabled"
          @click="changeOrder"
        >
          确认操作
        </button>
      </view>
    </view>
    <wechat-pay ref="wechatPay" />
  </view>
</template>

<script>
import { mapState } from 'vuex'
import WechatPay from '@/components/wechatPay.vue'
import { parseTime } from '@/utils/index.js'

export default {
  components: {
    WechatPay
  },
  data() {
    return {
      // 点击改奶的日期
      clickDay: '',
      // 停奶的天数集合
      selectedDays: [],
      // 选中改奶的商品Id
      selectedGoodId: '',
      // 每日配送的数量
      avgNumPreDay: 1,
      goodPrice: 0,
      // 订单编号
      orderNo: '',
      // 补差价的订单编号
      newOrderNo: '',
      // 配送商品的id
      deliveryGoodId: '',
      // loading加载 防重复操作
      loading: false,
      // 某个订奶的计划
      deliveryPlanList: [
        // {
        //   deliveryDate: '2020-06-24',
        //   deliveryStatus: 1
        // },
      ],
      // 换奶加载的商品列表
      goodList: [
        // {
        //   goodId: 1,
        //   goodImg: '/static/errorImage.jpg',
        //   goodImgs: ['/static/errorImage.jpg'],
        //   goodName: '低温鲜奶500ml',
        //   goodPrice: 10.00
        // }
      ],
      // 后台返回的补差价
      priceAmount: 0,
      // 分页
      pageSize: 10,
      pageNo: 1,
      // 能否加载更多
      loadingType: '',
      isAllChecked: false
    }
  },
  computed: {
    ...mapState(['userInfo']),
    // 补差价的金额
    sumPremium() {
      const selectGood = this.goodList.find(item => item.goodId === this.selectedGoodId)
      if(!selectGood) {
        return 0
      }
      const selectedGoodPrice = selectGood.goodPrice
      const sumPremium = (selectedGoodPrice - this.goodPrice) * this.avgNumPreDay * this.selectedDays.length
      return sumPremium
    },
    disabled() {
      return !(this.selectedGoodId && this.selectedDays.length > 0)
    }
  },
  filters: {
    formatDate(date) {
      return parseTime(date, '{m}-{d}')
    }
  },
  async onLoad(options) {
    this.orderNo = Number(options.orderNo)
    this.deliveryGoodId = Number(options.goodId)
    this.avgNumPreDay = Number(options.avgNumPreDay)
    this.goodPrice = Number(options.goodPrice)
    // getStopOrderPlan
    const orderPlan = await this.$api.json('getStopOrderPlan', { orderNo: this.orderNo, openId: this.userInfo.openId })
    this.deliveryPlanList = orderPlan.deliveryPlanList
    this.goodList = await this.$api.json('getGoods', { pageNo: this.pageNo, pageSize: this.pageSize })
  },
  methods: {
    // 加载更多
    loadMore() {

    },
    // 点击全选
    checkboxChange(e) {
      this.isAllChecked = e.target.value[0]
      if(e.target.value[0]) {
        const planList = []
        this.deliveryPlanList.map(item => {
          planList.push(item.deliveryDate)
        })
        this.selectedDays = planList
      } else {
        this.selectedDays = []
      }
    },
    // 选中送奶日期
    selectDeliveryDate(item, index) {
      if(item.isStopped) {
        return
      }
      if(this.loading) {
        return
      }
      const i = this.selectedDays.findIndex(v => v === item.deliveryDate)
      if(i > -1) {
        this.selectedDays.splice(i, 1)
      } else {
        this.selectedDays.push(item.deliveryDate)
      }
    },
    // 改奶选中商品
    changeGood(item) {
      if(this.loading) {
        return
      }
      if(this.goodPrice > item.goodPrice) {
        this.$api.msg('不可修改为低价产品')
        return
      }
      this.selectedGoodId = item.goodId
    },
    // 改奶
    async changeOrder() {
      if(!this.disabled) {
        this.loading = true
        uni.showLoading({
          title: ''
        })
        try {
          const res = await this.$api.json('calcChangeOrder', {
            openId: this.userInfo.openId,
            orderNo: this.orderNo,
            goodId: this.selectedGoodId,
            planDeliveryList: this.deliveryPlanList,
            priceAmount: this.sumPremium
          })
          this.priceAmount = res.priceAmount
          if(res.priceAmount === 0) {
            uni.hideLoading()
            this.$api.msg('修改成功')
            setTimeout(() => {
              this.loading = false
              uni.navigateBack()
            }, 200)
            return
          }
          this.newOrderNo = res.orderNo
          this.loading = false
          uni.hideLoading()
          this.$refs.wechatPay.toggleMask()
          this.$refs.wechatPay.orderNo = this.newOrderNo
        } catch (error) {
          console.log(error)
          this.loading = false
          uni.hideLoading()
        }
      }
    }
  }
}
</script>

<style lang="scss">
  .change-delivery-container {
    background-color: #ffffff;
    .good-list {
      width: 750rpx;
      padding: 20rpx;
      .good-item {
        width: 710rpx;
        height: 160rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: $font-base;
        color: $font-color-dark;
        border-bottom: 1px solid #cccccc;
        .good-item-info {
          height: 160rpx;
          display: flex;
          align-items: center;
          image {
            width: 120rpx;
            height: 120rpx;
            margin-right: 20rpx;
          }
          .good-item-info-r {
            height: 120rpx;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
          }
          .good-price {
            color: $base-color;
          }
        }
        .good-item-btn {
          width: 140rpx;
          height: 70rpx;
          line-height: 70rpx;
          text-align: center;
          color: $font-color-base;
          font-size: $font-base;
          border: 1px solid $font-color-base;
          border-radius: 10rpx;
        }
      }
    }
    
    .order-detail-btns {
      width: 750rpx;
      padding: 20rpx;
      position: fixed;
      bottom: 0;
      left: 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: #ffffff;
      // border-top: 1px solid #ccc;
      box-shadow: 0 -1px 5px rgba(0,0,0,.1);
      .amount-container {
        font-size: $font-sm;
      }
      .pay-amount {
        color: $base-color;
      }
      .amount-btn {
        display: flex;
        button {
          margin-left: 20rpx;
          font-size: $font-sm + 1rpx;
        }
      }
      .disabled {
        background-color: $font-color-disabled;
      }
    }
    
  }
  .active {
    background-color: $base-color;
    color: #ffffff !important;
    border-color: $base-color !important;
  }
  .stop-delivery-label {
    width: 750rpx;
    height: 120rpx;
    padding: 20rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-top: 1px solid #ccc;
    border-bottom: 1px solid #ccc;
    .left {
      font-size: $font-base;
      color: $font-color-dark;
      display: flex;
      align-items: center;
      .checked-box {
        margin-left: 20rpx;
      }
      .checked-box-value {
        transform: scale(0.6);
      }
    }
    .right {
      display: flex;
      align-items: center;
      color: $font-color-base;
      font-size: $font-base;
    }
  }
  .delivery-plan-container {
    width: 750rpx;
    height: 400rpx;
  }
  .delivery-plan {
    width: 750rpx;
    padding: 40rpx 25rpx;
    display: flex;
    flex-wrap: wrap;
    // justify-content: space-between;
    align-items: center;
    .delivery-day-item {
      width: 130rpx;
      height: 60rpx;
      line-height: 60rpx;
      border-radius: 8rpx;
      border: 1px solid #ccc;
      text-align: center;
      font-size: $font-base;
      color: $font-color-base;
      margin-right: 10rpx;
      margin-bottom: 10rpx;
    }
  }
</style>
